# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
uuid    = require 'uuid'
router = express.Router()
module.exports = router

router.get '/', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    where_clause = "(
        name like $1 or ipaddr like $1 or notes like $1
    )"
    # 查询记录总数
    await client.query "select count(*) as count from pay_hosts
        where #{ where_clause }", [
            '%' + res.locals.keyword + '%'
        ], defer err, result
    if err then done(client); return next(err)
    res.locals.total = result.rows[0].count

    # 查询当前页面中显示的记录
    await client.query "select * from pay_hosts where #{ where_clause }
        order by serial offset $2::int limit $3::int", [
            '%' + res.locals.keyword + '%',
            res.locals.offset,
            res.locals.page_rows
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.render 'hosts/index', records : result.rows


router.post '/switch', (req, res, next) ->
    res.type('json')
    for k in ['serial', 'uuid']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)
    await client.query \
        "select * from pay_hosts where serial = $1 and uuid = $2", [
            req.body.serial, req.body.uuid
        ], defer err, result
    if err then done(client); return next(err)
    done()
    if result.rows.length == 0
        return next(new Error('没有找到匹配的记录'))
    req.session.host = result.rows[0]
    res.json succ: true


router.get '/new', (req, res, next) ->
    res.locals.breadcrumbs.push 'title': '新增主机'
    res.render 'hosts/new', record: {}


router.post '/new', (req, res, next) ->
    for k in ['name', 'ipaddr', 'master']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "insert into pay_hosts (
            uuid, name, ipaddr, ipaddr_priv, master, notes
        ) values (
            $1, $2, $3, $4, $5, $6
        )", [
            uuid.v4(),
            req.body.name,
            req.body.ipaddr,
            req.body.ipaddr_priv,
            req.body.master is 'true',
            req.body.notes
        ], defer err, result
    if err then done(client); return next(err)

    # 清除缓存，重新获取主机列表菜单
    req.app.locals.hosts = null
    req.session.host = null

    # 如果当前主机设置为默认，则将其它主机设置为非默认(互斥)
    if req.body.master != 'true'
        done()
        return res.redirect '/hosts'
    await client.query \
        "update pay_hosts set master = false where ipaddr <> $1", [
            req.body.ipaddr,
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.redirect '/hosts'


router.get '/edit/:id', (req, res, next) ->
    res.locals.breadcrumbs.push 'title': '修改主机信息'

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)
    await client.query \
        "select * from pay_hosts
            where serial = $1 or uuid = $2", [
            parseInt(req.params.id) or 0,
            req.params.id
        ], defer err, result
    if err then done(client); return next(err)
    done()

    if result.rows.length != 1
        return next(new Error("查无此主机记录[#{req.params.id}]"))
    res.render 'hosts/edit', record: result.rows[0]


router.post '/edit', (req, res, next) ->
    for k in ['serial', 'uuid', 'name', 'ipaddr']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)
    await client.query \
        "update pay_hosts set name = $1, ipaddr = $2,
            ipaddr_priv = $3,
            master = $4, notes = $5
            where serial = $6 and uuid = $7", [
            req.body.name,
            req.body.ipaddr,
            req.body.ipaddr_priv,
            req.body.master is 'true',
            req.body.notes,
            req.body.serial,
            req.body.uuid
        ], defer err, result
    if err then done(client); return next(err)

    # 清除缓存，重新获取主机列表菜单
    req.app.locals.hosts = null
    req.session.host = null

    # 如果当前主机设置为默认，则将其它主机设置为非默认(互斥)
    if req.body.master != 'true'
        done()
        return res.redirect '/hosts'
    await client.query \
        "update pay_hosts set master = false where uuid <> $1", [
            req.body.uuid,
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.redirect '/hosts'


router.post '/delete', (req, res, next) ->
    res.type 'json'
    for k in ['serial', 'uuid']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err);
    await client.query \
        "delete from pay_hosts where serial = $1 and uuid = $2", [
            req.body.serial, req.body.uuid,
        ], defer err, result
    if err then done(client); return next(err);
    done()

    # 清除缓存，重新获取主机列表菜单
    req.app.locals.hosts = null
    req.session.host = null
    res.json succ: true, redirect: '/hosts'
